package com.it.tydic.estate.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Configuration
@EnableWebSecurity
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out=response.getWriter();
        ObjectMapper objectMapper=new ObjectMapper();
         if(exception instanceof LockedException){
            out.write(objectMapper.writeValueAsString(Result.error(CodeMsg.LOGIN_FORBIDDEN)));
        }else if(exception instanceof AccountExpiredException){
            out.write(objectMapper.writeValueAsString(Result.error(CodeMsg.LOGIN_EXPIARE)));
        }else{
            out.write(objectMapper.writeValueAsString(Result.error(CodeMsg.LOGIN_FAILURE)));
        }
        out.flush();
        out.close();
    }
}
